# 拓展视图集，继承了五个拓展类，可以实现增删改查多个方法功能,，还继承了GenericAPIView
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from book.modelserializer import BookModelSerialzier
from book.models import BookInfo
from rest_framework.response import Response

# 导入认证方法类
from rest_framework.authentication import BasicAuthentication,SessionAuthentication
# 导入权限类
from rest_framework.permissions import IsAuthenticated
# 导入排序过滤器类
from rest_framework.filters import OrderingFilter
# 导入自定义分页器
from book.utils import PageNum


class BookModelViewSet(ModelViewSet):
    # 因为ModelViewSet继承了GenericAPIView，所以可以指定两个属性
    serializer_class = BookModelSerialzier
    queryset = BookInfo.objects.all()

    # ModelViewSet继承了五个拓展，那么拓展类中封装的五个方法create，update，list，retrieve，destroy就被子类继承

    # # 认证属性，指定认证方法，只对当前视图有效
    # authentication_classes = [BasicAuthentication, SessionAuthentication]
    # # 权限属性，指定权限方法，只对当前视图有效
    # permission_classes = [IsAuthenticated]

    # 指定视图限流名
    throttle_scope = 'BookModelViewSet'

    # # 在视图中添加filter_fields属性，指定可以过滤的字段
    # # 127.0.0.1:8000/books/?btitle=西游记
    # filter_fields = ('btitle', 'bread')

    # 127.0.0.1:8000/books/?ordering=-bread
    # 指定过滤后端
    filter_backends = [OrderingFilter]
    # 指定过滤排序字段
    ordering_fields = ('id', 'bread', 'bpub_date')

    # 使用自定义分页器
    pagination_class = PageNum

    # methods 指定自定义方法对应的请求方式,
    # detail如果需要正则匹配id值(pk参数) 则detail=True
    # 如果不需要正则匹配id值 则detail=False
    @action(methods=['get'], detail=False)
    def book_last(self, request):
        # 制造的错误
        # 请求地址: 127.0.0.1:8000/books/book_last/
        # a = 1/0

        book = BookInfo.objects.last()
        ser = self.get_serializer(book)
        return Response(ser.data)
